package com.krazevina.luatgiaothong;

import com.sun.lwuit.Button;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.FocusListener;
import com.sun.lwuit.events.SelectionListener;
import com.sun.lwuit.layouts.BoxLayout;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;

public final class MainForm extends Form{
    TextArea txtSearch;
    Button btnsearch,btnlang;
    Label more;
    List lv;Button casi,name,loi;
    boolean searchoption=true;
    final int SIZEPERPAGE=20;
    
    InputStream inps;
    InputStreamReader ir;
    BufferedReader in;
    public MainForm() {
        lv = new List();
        lv.setListCellRenderer(new ListCellRender());
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        addHeaderAndFooter();
        pageMark = new int[1000];
        searching = new Label("Đang tìm...");
    }
    
    Vector result;
    int page = 0;Label searching;
    boolean next;
    
    void newLv(){
        removeComponent(lv);
        lv = new List();
        lv.setListCellRenderer(new ListCellRender());
        lv.setPreferredH(getHeight()-90);
        addComponent(1,lv);
        lv.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                System.out.println("index:"+lv.getSelectedIndex()+"/"+result.size());
                if(lv.getSelectedIndex()==result.size()&&next){
                    page++;
                    more.setText("Đang tìm...");
                    repaint();
                    new findName(lastSearch, page).start();
                }
            }
        });
        lv.addSelectionListener(new SelectionListener() {
            public void selectionChanged(int i, int i1) {
                lastfocus = i1;
            }
        });
    }
    
    
    int lastfocus=0;
    int[]pageMark;
    String lastSearch="pho";
    /**
     * searchType = 0 : search by song name
     *            = 1 : search by artist name
     *            = 2 : search by code
     *            = 3 : search by lyrics
     */
    int searchType;
    
    void addHeaderAndFooter(){
        Container searchbox = new Container(new BoxLayout(BoxLayout.X_AXIS));
        searchbox.setPreferredH(45);
        txtSearch = new TextArea(lastSearch);
        txtSearch.setPreferredW((int)(getWidth()*0.55f));
        txtSearch.addFocusListener(new FocusListener() {
            public void focusGained(Component cmpnt) {
                if(txtSearch.getText().startsWith("Tên bài")||
                    txtSearch.getText().startsWith("Ca sĩ")||
                    txtSearch.getText().startsWith("Mã")||
                    txtSearch.getText().startsWith("Lời"))
                    txtSearch.setText("");
            }
            public void focusLost(Component cmpnt) {
                if(txtSearch.getText().length()==0){
                    switch(searchType){
                        case 0:txtSearch.setText("Tên bài");break;
                        case 1:txtSearch.setText("Ca sĩ");break;
                        case 2:txtSearch.setText("Mã");break;
                        case 3:txtSearch.setText("Lời");break;
                    }
                }
            }
        });
        btnlang = new Button("Vie");
        try {
            Image i = Image.createImage("/btnsearch.png");
            btnsearch = new Button(i);
        } catch (IOException ex) {
            btnsearch = new Button("Tìm");
        }
        try {
            Image i;
            i = Image.createImage("/back.png");
            searchbox.getStyle().setBgImage(i);
            searchbox.getStyle().setBgTransparency(255);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        S.sets(txtSearch);
        S.setBtnSearchStyle(btnsearch);
        S.setBtnLangStyle(btnlang);
        searchbox.addComponent(btnsearch);
        searchbox.addComponent(txtSearch);
        searchbox.addComponent(btnlang);
        addComponent(0,searchbox);
        btnsearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                lastSearch = txtSearch.getText();
                if(txtSearch.getText().length()>1){
                    result = new Vector();
                    page = 0;
                    newLv();
                    searching.setText("Đang tìm...");
                    lv.addItem(searching);
                    repaint();
                    new findName(""+txtSearch.getText(),page).start();
                }
            }
        });
        btnlang.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                searchoption = !searchoption;
                if(searchoption)btnlang.setText("Vie");
                else btnlang.setText("Eng");
                repaint();
            }
        });
        lv.setPreferredH(getHeight()-90);
        addComponent(lv);
        
        Container bot = new Container(new BoxLayout(BoxLayout.X_AXIS));
        bot.setPreferredH(45);
        bot.getStyle().setBgColor(0x7d7d7d);
        bot.getStyle().setBgTransparency(255);
        bot.getStyle().setAlignment(Label.CENTER);
        
        try{
            casi = new Button(Image.createImage("/casideactiv.png"));
            name = new Button(Image.createImage("/nameactive.png"));
            loi = new Button(Image.createImage("/loideactiv.png"));
            S.setBtnBotStyle(casi);S.setBtnBotStyle(name);S.setBtnBotStyle(loi);
            casi.getUnselectedStyle().setMargin(0, 0, (getWidth()-44*3)/2, 0);
            casi.getPressedStyle().setMargin(0, 0, (getWidth()-44*3)/2, 0);
            casi.getSelectedStyle().setMargin(0, 0, (getWidth()-44*3)/2, 0);
            casi.getStyle().setMargin(0, 0, (getWidth()-48*3)/2, 0);
            bot.addComponent(casi);
            bot.addComponent(name);
            bot.addComponent(loi);
            casi.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    try{
                        casi.setIcon(Image.createImage("/casiactive.png"));
                        name.setIcon(Image.createImage("/namedeactiv.png"));
                        loi.setIcon(Image.createImage("/loideactiv.png"));
                    }catch(Exception e){}
                    searchType = 1;
                    repaint();
                }
            });
            name.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    try{
                        name.setIcon(Image.createImage("/nameactive.png"));
                        casi.setIcon(Image.createImage("/casideactiv.png"));
                        loi.setIcon(Image.createImage("/loideactiv.png"));
                    }catch(Exception e){}
                    searchType = 2;
                    repaint();
                }
            });
            loi.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    try{
                        loi.setIcon(Image.createImage("/loiactive.png"));
                        casi.setIcon(Image.createImage("/casideactiv.png"));
                        name.setIcon(Image.createImage("/namedeactiv.png"));
                    }catch(Exception e){}
                    searchType = 3;
                    btnlang.setText("Vie");
                    searchoption = true;
                    repaint();
                }
            });
        }catch(Exception e){
            e.printStackTrace();
        }
        addComponent(2,bot);
    }
    
    void showResult(){
        newLv();
        Label name; Label lyric,ID;
        Container out,child;
        Song item;
        System.out.println("result:"+result.size());
        for(int i=0;i<result.size();i++){
            item = (Song) result.elementAt(i);
            out = new Container(new BoxLayout(BoxLayout.Y_AXIS));
            child = new Container(new BoxLayout(BoxLayout.X_AXIS));
            
            name = new Label(item.name);
            lyric = new Label(item.lyric);
            ID = new Label(""+item.ID);
            S.setTrans1(lyric,0x000000);
            S.setTrans1(ID,0x05b3e8);
            S.setTrans(name);
            
            child.addComponent(ID);
            child.addComponent(lyric);
            
            out.addComponent(name);
            out.addComponent(child);
            lv.addItem(out);
        }
        if(result.size()%SIZEPERPAGE==0&&result.size()>0){
            more = new Label("Tiếp");
            lv.addItem(more);
        }
        lv.setItemGap(1);
        lv.setSelectedIndex(page*SIZEPERPAGE, true);
        repaint();
    }
    
    
    class findName extends Thread{
        String searchterm;
        int page;
        public findName(final String re, final int page){
            searchterm = re;this.page = page;
        }
        public void run(){
            next = false;
            System.out.println("Search:"+searchterm);
            searchterm = searchterm.toLowerCase().trim();
            inps = getClass().getResourceAsStream("/song.txt");
            try{
                ir = new InputStreamReader(inps,"UTF-8");
                in = new BufferedReader(ir);
                String s1="";
                Song song;
                int i1;
                System.out.println("from "+pageMark[page]);
                for(i1=pageMark[page];i1<13997;i1++){
                    s1 = in.readLine();
                    if(s1.indexOf(""+searchterm)>=0){
                        song = new Song(s1);
                        
                        if(searchType==0&&song.isName(searchterm,searchoption)<10){
                            result.addElement(song);
                            if(result.size()>=(page+1)*SIZEPERPAGE){
                                pageMark[page+1] = i1;
                                next = true;
                                break;
                            }
                        }
                        if(searchType==1&&song.isArtist(searchterm,searchoption)<10){
                            result.addElement(song);
                            if(result.size()>=(page+1)*SIZEPERPAGE){
                                pageMark[page+1] = i1;
                                next = true;
                                break;
                            }
                        }
                        if(searchType==2&&song.isCode(searchterm,searchoption)<10){
                            result.addElement(song);
                            if(result.size()>=(page+1)*SIZEPERPAGE){
                                pageMark[page+1] = i1;
                                next = true;
                                break;
                            }
                        }
                        if(searchType==3&&song.isLyrics(searchterm)<10){
                            result.addElement(song);
                            if(result.size()>=(page+1)*SIZEPERPAGE){
                                pageMark[page+1] = i1;
                                next = true;
                                break;
                            }
                        }
                    }
                }
                if(result.size()<=0){
                    searching.setText("Không có kết quả.");
                    repaint();
                }
                else showResult();
            }catch(Exception e){
            }
        }
    }
}
